<?php

// +----------------------------------------------------------------------
// | 公开控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\v3;

use app\common\model\Area as AreaModel;
use app\event\index\Task as TaskEvent;
use app\event\ucenter\User as UserEvent;
use app\model\ucenter\UserOauth as UserOauthModel;
use app\model\ucenter\Sms as SmsModel;
use app\event\ucenter\Notice as NoticeEvent;
use app\model\file\Image as ImageModel;
use think\Exception;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;
use think\facade\Log;

class Foreign extends Common
{


    /**
     * 提交任务
     */
    public function task()
    {
        if ($this->request->isPost()) {
            $event = new TaskEvent();
            $data = $event->add($this->request->param(), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);

    }

    /**
     * 提交任务
     */
    public function quick_mobile()
    {
//        $insert['out_id'] = $this->request->param('clientid');
//        $insert['channel'] = 'one_mobile';
//        $insert['type'] = 'login';
//        $insert  = SmsModel::create($insert);
//        $data['token'] = $insert;
//        if ($this->app_version == '3.1.0')
//        {
            $data['is_show'] = 0;
            $data['show_quick_mobile'] = 1;
//        }else{
//            $data['is_show'] = 0;
//            $data['show_quick_mobile'] = 0;
//        }
        return $this->successAjax($data);
    }
    /**
     * 短信一键登录
     * @return mixed|string
     */
    public function quick_one_mobile()
    {
        if ($this->request->isPost()) {
            $user_event = new UserEvent();
            $data = $user_event->login($this->request->param(), 'api', 'one_mobile');
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 第三方登录
     * @return mixed|string
     */
    public function bind()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            $user_event = new UserEvent();
            $data = $user_event->oauthBind($this->request->param());
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 第三方登录
     * @return mixed|string
     */
    public function service()
    {
        $data['cate'] = Db::name('service_block')->where('id', '<>', 2)->where('id', '<>', 5)->field('id,block as name')->select();
        $data['service'] = Db::name('service')->select();
        $data['server_link'] = 'https://work.weixin.qq.com/kfid/kfccd51f821bad19244';
        return $this->successAjax($data);
    }

    /**
     * 第三方登录
     * @return mixed|string
     */
    public function oauthLogin(): mixed
    {
        if ($this->request->isPost()) {
            // 安全验证码
            $user_event = new UserEvent();
            $data = $user_event->oauthLogin($this->request->param());
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 用户注册
     * @return mixed|string
     */
    public function register()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            $result = $this->validate($this->request->post(), '\app\validate\ucenter\User.register');
            if (true !== $result) {
                $data['code'] = 20002;
                $data['message'] = $result;
            } else {
                $user_event = new UserEvent();
                $data = $user_event->register($this->request->param(), 'api');
            }
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 用户验证码
     * @return mixed|string
     */
    public function code()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            // 需要填写验证码
            $data = $this->request->post();
            $channel = $this->request->param('safe_check_type', 'mobile');
            if ($channel == 'mobile') {
                $validate = $this->validate($data, '\app\validate\ucenter\Sms');
            } else {
                $validate = $this->validate($data, '\app\validate\ucenter\Email.send');
            }
            if (true !== $validate) {
                $data['code'] = 20002;
                $data['message'] = $validate;
            } else {
                $data = NoticeEvent::safeCode($this->request->param(), $this->user, $channel);
            }
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错1误';
        }
        return $this->autoAjax($data);
    }


    public function sms()
    {
        $data['code'] = 1;
        $data['message'] = '请求错误';

        return $this->autoAjax($data);
    }

    /**
     * 用户登陆.
     * @return mixed|string
     */
    public function login()
    {
        if ($this->request->isPost()) {
            // 安全验证码

//                $account = $this->request->request('account');
//                $password = $this->request->request('password');
//                if (!$account || !$password) {
//                    $this->error(__('Invalid parameters'));
//                }
//                $ret = $this->auth->login($account, $password);
//                if ($ret) {
//                    $data = ['userinfo' => $this->auth->getUserinfo()];
//                    $this->success(__('Logged in successful'), $data);
//                } else {
//                    $this->error($this->auth->getError());
//                }

            // 图像验证码
            $result = $this->validate($this->request->post(), 'app\validate\ucenter\User.login');
            if (true !== $result) {
                $data['code'] = 20002;
                $data['message'] = $result;
            } else {
                $user_event = new UserEvent();
                $data = $user_event->login($this->request->param(), 'api');
            }
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    /**
     * 短信用户登陆.
     * @return mixed|string
     */
    public function quick()
    {
        if ($this->request->isPost()) {
            $user_event = new UserEvent();
            $data = $user_event->login($this->request->param(), 'api', 'sms_code');
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 短信用户登陆.
     * @return mixed|string
     */
    public function quicko()
    {
        if ($this->request->isPost()) {
            $user_event = new UserEvent();
            $data = $user_event->login($this->request->param(), 'api', 'wx');
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 用户登陆.
     * @return mixed|string
     */
    public function forget()
    {
        if ($this->request->isPost()) {
            // 安全验证码

            $validate = $this->validate($this->request->post(), 'app\validate\ucenter\User.forget');
            if (true !== $validate) {
                $data['code'] = 20002;
                $data['message'] = $validate;
            } else {
                $user = new UserEvent();
                $data = $user->forget($this->request->post());
            }
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    /**
     * 用户退出
     * @return mixed|string
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $data['code'] = 0;
            $data['message'] = '成功';
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    /**
     * 用户登陆.
     * @return mixed|string
     */
    public function area()
    {
        $data = AreaModel::where('pid', 0)->field('id,id as value,name as text')->select()->toArray();
        foreach ($data as $index => $datum) {
            $cc = AreaModel::where('pid', $datum['id'])->field('id,id as value,name as text')->select()->toArray();
            if ($cc) {
                $data[$index]['children'] = $cc;
                foreach ($cc as $k => $v) {
                    $dd = AreaModel::where('pid', $v['id'])->field('id,id as value,name as text')->select()->toArray();
                    if ($dd) {
                        $data[$index]['children'][$k]['children'] = $dd;
                    }
                }
            }
        }
        return $this->successAjax($data);
    }


    /**
     * 微信小程序登录解析
     */
    public function jscode2session()
    {
        $mini = new SnsMini();
        $result = $mini->jscode2session($this->request->get('code'));
        if (!isset($result['errcode'])) {
            // 查询是否已经注册。没有则注册
            $oauth = UserOauthModel::where('open_id', $result['openid'])->where('status', 1)->find();
            if ($oauth) {
                // 更新session_key
                $oauth['access_token'] = $result['session_key'];
                $oauth->save();
            } else {
                // 保存session_key
                $oauth = [];
                $oauth['open_id'] = $result['openid'];
                $oauth['channel'] = 'wechat_lite';
                $oauth['access_token'] = $result['session_key'];
                if (isset($result['unionid'])) {
                    $oauth['unionid'] = $result['unionid'];
                }
                UserOauthModel::create($oauth);
            }
            unset($result['session_key']);
            $data['code'] = 0;
            $data['data'] = $result;
        } else {
            $data['code'] = $result['errcode'];
            $data['message'] = $result['errmsg'];
        }

        return $this->autoAjax($data);
    }

    public function shareTicket()
    {
        try {
            $oauth = UserOauthModel::get([
                'open_id' => $this->request->param('open_id')
            ]);
            $appid = Config::get('mini_program.appid');
            $sessionKey = $oauth['access_token'];
            $encryptedData = $this->request->param('encryptedData');
            $iv = $this->request->param('iv');
            include app()->getRootPath() . 'extend/wechat/wxBizDataCrypt.php';
            $pc = new \WXBizDataCrypt($appid, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $result);
            if ($errCode == 0) {
                $result = json_decode($result, true);
                if (isset($result['phoneNumber'])) {
                    $oauth->user['mobile'] = $result['phoneNumber'];
                    $oauth->user->save();
                }
                $data['code'] = 0;
                $data['data'] = $result;
            } else {
                $data['code'] = 3;
                $data['message'] = $errCode;
            }
        } catch (Exception $e) {
            $data['code'] = 3;
            $data['message'] = $e->getMessage();
        }

        return $this->autoAjax($data);
    }

    /**
     * 微信信息解析及登录
     */
    public function wechatCrypt()
    {
        try {
            $oauth = UserOauthModel::where('open_id', $this->request->param('open_id'))->where('status', 1)->find();
            $encryptedData = $this->request->param('encryptedData');
            $iv = $this->request->param('iv');
            include app()->getRootPath() . 'extend/wechat/wxBizDataCrypt.php';
            $pc = new \WXBizDataCrypt(Config::get('mini_program.appid'), $oauth['access_token']);
            $errCode = $pc->decryptData($encryptedData, $iv, $result);
            if ($errCode == 0) {
                $result = json_decode($result, true);
                $oauth['avatar'] = $result['avatarUrl'];
                $oauth['nickname'] = $result['nickName'];
                $oauth['sex'] = $result['gender'];
                $oauth['info'] = $result;
                if (isset($result['unionId'])) {
                    $oauth['unionid'] = $result['unionId'];
                }
                $event = new UserEvent();
                // 完善信息
                if ($oauth->user) {
                    $result = $event->oauthLogin($oauth->user, '小程序');
                    if (0 != $result['code']) {
                        throw new Exception($result['message']);
                    }
                    $user = $result['data'];
                } else {
                    if ($this->request->post('invite_user_id', 0)) {
                        $oauth['invite_id'] = $this->request->post('invite_user_id');
                    }
                    $result = $event->register($oauth, 'oauth');
                    if (0 != $result['code']) {
                        throw new Exception($result['message']);
                    }
                    $user = $result['data'];
                    $oauth['user_id'] = $user['id'];
                }
                $oauth->save();
                $data['code'] = 0;
                $data['data'] = $user;
            } else {
                $data['code'] = 3;
                $data['message'] = $errCode;
            }
        } catch (Exception $e) {
            $data['code'] = 3;
            $data['message'] = $e->getMessage();
        }

        return $this->autoAjax($data);
    }

}
